//
//  TutorMainControl.m
//  blackjack
//
//  Created by kyocooro on 4/2/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "TutorMainControl.h"
#import "EpImageProcessor.h"
#import <QuartzCore/QuartzCore.h>
#import "MusicManager.h"
#import "MusicPlayer.h"
#import "SoundManager.h"

@interface TutorMainControl(Private)

#define USER_CARD_POS_X		220
#define USER_CARD_POS_Y		160

#define DEALER_CARD_POS_X	220
#define DEALER_CARD_POS_Y	50

#define NUMBER_CARD_VALUE	13
#define NUMBER_CARD_TYPE	4

#define DECK_MODE_MULTI		0
#define DECK_MODE_SINGLE	1

int MultiTableValue[][10] = {
	{1, 1,  1,  1,  1,  1,  1,  1,  1,  1},
	{1, 3, 	3, 	3, 	3, 	1, 	1, 	1, 	1, 	1},
	{3, 3, 	3, 	3, 	3, 	3, 	3, 	3, 	1, 	1},
	{3, 3, 	3, 	3, 	3, 	3, 	3, 	3, 	3, 	1},
	{1, 1, 	0, 	0, 	0, 	1, 	1, 	1, 	1, 	1},
	{0, 0, 	0, 	0, 	0, 	1, 	1, 	1, 	1, 	1},
	{0, 0, 	0, 	0, 	0, 	1, 	1, 	1, 	1, 	1},
	{0, 0, 	0, 	0, 	0, 	1, 	1, 	1, 	1, 	1},
	{0, 0, 	0, 	0, 	0, 	1, 	1, 	1, 	1, 	1},
	{0, 0, 	0, 	0, 	0, 	0, 	0, 	0, 	0, 	0},
	{1, 1,  1,  3,  3,  1,  1,  1,  1,  1},
	{1, 1, 	1, 	3, 	3, 	1, 	1, 	1, 	1, 	1},
	{1, 1,  3, 	3, 	3, 	1, 	1, 	1, 	1, 	1},
	{1, 1, 	3, 	3, 	3, 	1, 	1,	1, 	1, 	1},
	{1, 3, 	3, 	3, 	3, 	1, 	1, 	1, 	1, 	1},
	{0, 3,	3, 	3, 	3, 	0, 	0, 	1, 	1, 	1},
	{0, 0, 	0, 	0, 	0, 	0, 	0, 	0, 	0, 	0},
	{0, 0, 	0,	0, 	0, 	0, 	0, 	0, 	0, 	2},
	{2, 2,  2,  2,  2,  2,  1,  1,  1,  1},
	{2, 2,  2,	2, 	2, 	2, 	1, 	1, 	1, 	1},
	{1, 1, 	1, 	2, 	2, 	1, 	1, 	1, 	1, 	1},
	{3, 3, 	3, 	3, 	3, 	3, 	3, 	0, 	1, 	1},
	{2, 2, 	2, 	2, 	2, 	1, 	1, 	1, 	1, 	1},
	{2, 2, 	2, 	2, 	2, 	2, 	1, 	1, 	1, 	1},
	{2, 2, 	2, 	2, 	2, 	2, 	2, 	2, 	0, 	2},
	{2, 2, 	2, 	2, 	2, 	0, 	2, 	2, 	0, 	0},
	{0, 0, 	0, 	0, 	0, 	0, 	0, 	0, 	0, 	0},
	{2, 2, 	2, 	2, 	2, 	2, 	2, 	2, 	2, 	2}};

int KOCounting[] = {0,-1,1,1,1,1,1,1,0,0,-1,-1,-1,-1};
int HiLoCounting[] = {0,-1,1,1,1,1,1,0,0,0,-1,-1,-1,-1};
int HiOptICounting[] = {0,0,0,1,1,1,1,0,0,0,-1,-1,-1,-1};
int HiOptIICounting[] = {0,0,1,1,2,2,1,1,0,0,-2,-2,-2,-2};
int OmegaCounting[] = {0,0,1,1,2,2,2,1,0,-1,-2,-2,-2,-2};

int cardDeck_[NUMBER_CARD_VALUE + 1][4];
int cardArr_[NUMBER_CARD_VALUE + 1];

int *currentCardCounting;
int **currentTableValue;

int dealerCards_[5];
int playerCards_[5];
int tmpPlayerCards_[5];

int dealerCardCount_;
int playerCardCount_;
int tmpPlayerCardCount_;

UIImageView *playerCardsView_[5];
UIImageView *dealerCardsView_[5];
//UIImageView *tmpPlayerCardsView_[5];
UIImageView *faceupCardView;

int currentDeckMode;
int numberOfDeck_;
int countDealtCard_;
int runningCountValue_;
float trueCountValue_;


- (UIImage *)getCard:(int)no andType:(int)type;
- (void)dealCardTo:(CGPoint)pos withView:(UIView *)view;

- (void)dealToDealer:(int)nth;
- (void)dealToPlayer:(int)nth;

- (void)initAll;
- (void)showActionAdviceStatement;
- (void)showBettingAdviceStatement;

- (void)disableAll;
- (void)enabledAll;
- (void)dealAtFirst:(NSTimer *)t;
- (void)viewResult:(NSTimer *)t;
- (void)endOneGame;
- (void)reCountValue;
- (void)dealerGetCard;
- (void)playerWin;
- (void)playerLoose;
- (void)resetDeck;

- (int)countDealerHand;
- (int)countPlayerHand;
//- (int)countTempHand;

@end


@implementation TutorMainControl

@synthesize delegate;

#pragma mark INIT_OR_RESTART
- (void)initAll {
	numberOfDeck_ = 6;
	
	countDealtCard_ = 0;
	runningCountValue_ = 0;
	trueCountValue_ = 0.0;
	
	playerCardCount_ = 0;
	dealerCardCount_ = 0;
	tmpPlayerCardCount_ = 0;
	
	for(int i = 1; i <= NUMBER_CARD_VALUE; i++) {
		cardArr_[i] = 0;
		for(int j = 0; j < NUMBER_CARD_TYPE; j++) {
			cardDeck_[i][j] = numberOfDeck_;
		} 
	}	
}
- (void)resetDeck {
	for(int i = 1; i <= NUMBER_CARD_VALUE; i++) {
		cardArr_[i] = 0;
		for(int j = 0; j < NUMBER_CARD_TYPE; j++) {
			cardDeck_[i][j] = numberOfDeck_;
		} 
	}
}

#pragma mark EVENT_HANDLE

- (IBAction)hitBtnTouched {	
	//[self disableAll];
	[hitBtn_ setEnabled:NO];
	[self dealToPlayer:playerCardCount_];
	playerCardCount_++;
	if([self countPlayerHand] > 21) {
		[self playerLoose];
		[actionAdviceStat_ setText:@""];
		return;
	}
	if(playerCardCount_ == 5) {
		[actionAdviceStat_ setText:@""];
		[self dealerGetCard];
	}
	
}
- (IBAction)standBtnTouched {
	[standBtn_ setEnabled:NO];
	//[self disableAll];
	
	[self dealerGetCard];
}
- (IBAction)backMainMenuBtnTouched {
	[delegate backToMainMenu];
}
- (IBAction)dealBtnTouched {	
	tick_ = 0;
	//[self disableAll];
	[dealBtn_ setEnabled:NO];
	[NSTimer scheduledTimerWithTimeInterval:0.5f
											 target:self
										   selector:@selector(dealAtFirst:)
										   userInfo:nil 
											repeats:YES];
	
	
	
}
- (IBAction)splitBtnTouched {

}
- (IBAction)doubleBtnTouched {

}
- (IBAction)musicBtnTouched {
	[delegate viewMusicPicker];
}

- (IBAction)chooseCountBtnTouched {
	[self disableAll];
	[chooseSystemBtn_ setHidden:YES];
	[popup_ setHidden:NO];
	[popup_ setUserInteractionEnabled:YES];
	
}

- (void)chooseCountingSystem:(int)k {
	[popup_ setHidden:YES];
	//[self enabledAll];
	[chooseSystemBtn_ setHidden:NO];
	switch (k) {
		case KO_COUNT:
			[curCardCount_ setText:@"KO system"];
			currentCardCounting = KOCounting;
			break;
		case HILO_COUNT:
			[curCardCount_ setText:@"HiLo system"];
			currentCardCounting = HiLoCounting;
			break;
		case HIOPT_I_COUNT:
			[curCardCount_ setText:@"Hi Opt I system"];
			currentCardCounting = HiOptICounting;
			break;
		case HIOPT_II_COUNT:
			[curCardCount_ setText:@"Hi Opt II system"];
			currentCardCounting = HiOptIICounting;
			break;
		case OMEGA_COUNT:
			[curCardCount_ setText:@"Omega system"];
			currentCardCounting = OmegaCounting;
			break;
		default:
			break;
	}
	[self reCountValue];
	if(runningCountValue_ != 0) {
		[self showBettingAdviceStatement];
	}
}

#pragma mark PRIVATE_PROCESS

- (int)countDealerHand {
	int sum = 0;
	for(int i = 0; i < dealerCardCount_; i++) {
		if(dealerCards_[1] < 10)
			sum += dealerCards_[i];
		else {
			sum += 10;
		}
	}
	return sum;
}

- (int)countPlayerHand {
	int sum = 0;
	for(int i = 0; i < playerCardCount_; i++) {
		if(playerCards_[i] < 10) {
			sum += playerCards_[i];
		}
		else {
			sum += 10;
		}
	}
	return sum;
}

- (void)endOneGame {
	[tooltip.view setHidden:YES];
	for(int i = 1; i < 5; i++) {
		[playerCardsView_[i] setHidden:YES];
		[playerCardsView_[i] setFrame:animator_.frame];
		[dealerCardsView_[i] setHidden:YES];
		[dealerCardsView_[i] setFrame:animator_.frame];
		//[tmpPlayerCardsView_[i] setHidden:YES];
	}
	[playerCardsView_[0] setHidden:YES];
	[dealerCardsView_[0] setHidden:YES];
	[playerCardsView_[0] setFrame:animator_.frame];
	//[faceupCardView setHidden:YES];
//	[faceupCardView setFrame:animator_.frame];
	if(countDealtCard_ % 52 == 8) {
		numberOfDeck_--;
		[remainDeck_ setText:[NSString stringWithFormat:@"remaining deck: %d",numberOfDeck_]];
		
	}
	
	if(countDealtCard_ >= 297) {
		numberOfDeck_ = 6;
		[remainDeck_ setText:[NSString stringWithFormat:@"remaining deck: %d",numberOfDeck_]];
		[self resetDeck];
	}
	[self enabledAll];
	[hitBtn_ setHidden:YES];
	[standBtn_ setHidden:YES];
	[splitBtn_ setHidden:YES];
	[doubleBtn_ setHidden:YES];
	
	[dealBtn_ setHidden:NO];
	
	[actionAdviceStat_ setText:@""];
		
}

- (void)playerLoose {
	tick_ = 0;
	[matchResult_ setText:@"You Loose"];
	[NSTimer scheduledTimerWithTimeInterval:1.5f
											 target:self
										   selector:@selector(viewResult:) 
										   userInfo:nil 
											repeats:YES];	
}

- (void)playerWin {
	tick_ = 0;
	[matchResult_ setText:@"You Win"];
	[NSTimer scheduledTimerWithTimeInterval:1.5f
											 target:self
										   selector:@selector(viewResult:) 
										   userInfo:nil 
											repeats:YES];	
}

- (void)dealerGetCard {
	//[faceupCardView setHidden:YES];
	[dealerCardsView_[0] setHidden:NO];
	while([self countDealerHand] < 17) {
		dealerCardCount_++;
		[self dealToDealer:dealerCardCount_];
	}
	int tmp = [self countDealerHand];
	if(tmp > 21 || tmp <= [self countPlayerHand]) {
		[self playerWin];
	}
	else {
		[self playerLoose];
	}
}

- (void)reCountValue {
	runningCountValue_ = 0;
	for(int i = 1; i <= NUMBER_CARD_VALUE; i++) {
		runningCountValue_ += (cardArr_[i] * currentCardCounting[i]);
	}
	trueCountValue_ = runningCountValue_ / (float)numberOfDeck_;
	[trueCount_ setText:[NSString stringWithFormat:@"True count:%.1f",trueCountValue_]];
	[runCount_ setText:[NSString stringWithFormat:@"Running count:%d",runningCountValue_]];
}

- (void)dealAtFirst:(NSTimer *)t {
	tick_++;
	switch (tick_) {
		case 1:
			//[self dealToDealer:0];
			[self dealToPlayer:0];
			break;
		case 2:
			//[self dealToPlayer:0];
			break;
		case 3:
			[self dealToPlayer:1];
			break;
		case 4:			
			[self dealToDealer:1];
			break;
		case 5:
			//[self showActionAdviceStatement];
			//[self enabledAll];
			[hitBtn_ setHidden:NO];
			[standBtn_ setHidden:NO];
			
			[dealBtn_ setHidden:YES];
			
			dealerCardCount_ = 2;
			playerCardCount_ = 2;
			NSLog(@"%d  %d", playerCards_[0], playerCards_[1]);
			if((playerCards_[0] == 1 && playerCards_[1] >= 10) || (playerCards_[1] == 1 && playerCards_[0] >= 10)) {
				[self playerWin];
				[t invalidate];
				return;
			}
			[self showActionAdviceStatement];
			[t invalidate];
			break;
		default:
			break;
	}
}

- (UIImage *)getCard:(int)no andType:(int)type {
	UIImage *deck = [UIImage imageNamed:@"classic-playing-cards.png"];
	CGRect cardRect = CGRectMake((no - 1) * 73, type * 98, 72, 98);
	return [EpImageProcessor createSubImage:deck withRect:cardRect];
}
- (void)dealToDealer:(int)nth {
	int value, type;
	while(TRUE) {
		value = arc4random() % 13 + 1;
		type  = arc4random() % 4;
		if(cardDeck_[value][type] > 0) {
			cardDeck_[value][type]--;
			break;
		}
	}
	countDealtCard_ ++;
	dealerCards_[nth] = value;
	
	runningCountValue_ += currentCardCounting[value];	
	trueCountValue_  = runningCountValue_ / (float)numberOfDeck_;
	[trueCount_ setText:[NSString stringWithFormat:@"True count:%.1f",trueCountValue_]];
	[runCount_ setText:[NSString stringWithFormat:@"Running count:%d",runningCountValue_]];
	[self showBettingAdviceStatement];
	
	[matchResult_ setText:[NSString stringWithFormat:@"%d", currentCardCounting[value]]];
	
	cardArr_[value]++;	
	[dealerCardsView_[nth] setImage:[self getCard:value andType:type]];
	//if(nth != 0) {
	if(nth == 0) [dealerCardsView_[nth] setHidden:YES];
	else {
		[dealerCardsView_[nth] setHidden:NO];
	}
		[self dealCardTo:CGPointMake(DEALER_CARD_POS_X + nth*10, DEALER_CARD_POS_Y ) withView:dealerCardsView_[nth]];
	
	//}
	//else {
//		[self dealCardTo:CGPointMake(DEALER_CARD_POS_X, DEALER_CARD_POS_Y) withView:faceupCardView];
//	}
	
}
- (void)dealToPlayer:(int)nth {
	int value, type;
	while(TRUE) {
		value = arc4random() % 13 + 1;
		type  = arc4random() % 4;
		if(cardDeck_[value][type] > 0) {
			cardDeck_[value][type]--;
			break;
		}
	}
	
	runningCountValue_ += currentCardCounting[value];	
	trueCountValue_  = runningCountValue_ / (float)numberOfDeck_;
	[trueCount_ setText:[NSString stringWithFormat:@"True count: %.1f",trueCountValue_]];
	[runCount_ setText:[NSString stringWithFormat:@"Running count: %d",runningCountValue_]];
	[self showBettingAdviceStatement];
	
	[matchResult_ setText:[NSString stringWithFormat:@"%d", currentCardCounting[value]]];
	
	countDealtCard_++;
	playerCards_[nth] = value;
	cardArr_[value]++;
	[playerCardsView_[nth] setImage:[self getCard:value andType:type]];
	[playerCardsView_[nth] setHidden:NO];
	[self dealCardTo:CGPointMake(USER_CARD_POS_X + nth*10, USER_CARD_POS_Y) withView:playerCardsView_[nth]];
	[self showActionAdviceStatement];
}
- (void)dealCardTo:(CGPoint)pos withView:(UIView *)view{
	
	[SoundManager playSoundTrack:@"CardSlide"];
	CGRect frame = view.frame;
	frame.origin = pos;// final y destination
	
	[UIView beginAnimations:@"movingCard" context:nil];
	[UIView setAnimationDuration:.3];
	[view setFrame:frame];
	[UIView commitAnimations];
	[hitBtn_ setEnabled:YES];
	//[self enabledAll];
	
}
- (void)animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)flag {
	
}

- (int)getValueOfActionByDealerCard:(int)dealer PlayerCardsArr:(int *)playerArr number:(int)n {
	int row, col;
	if(dealer == 1) {
		col = 9;
	}
	else if(dealer >= 10) {
		col = 8;
	}
	else {
		col = dealer - 2;
	}
	int sum = [self countPlayerHand];
	NSLog(@"sum = %d",sum);
	if(playerCardCount_ > 2) {
		if(sum < 8) return 1;
		row = sum - 8;
		if(row > 9) row = 9;
	}
	else {
		if(sum < 8 && (playerArr[1] != 1 && playerArr[0] != 1) && playerArr[0] != playerArr[1]) {
			return 1;
		}
		else {
			if(playerArr[0] == 1 || playerArr[1] == 1) {
				if(sum == 2) row = 27;
				else row = sum - 3 + 10;
			}			
			else if(playerArr[0] == playerArr[1]) {
				// 18 is the position in table where 2 cards value is both 2
				row = playerArr[0] + 18 - 2;
			}
			else {
				row = sum - 8;
				if(row > 9) row = 9;
			}
		}
	}
	NSLog(@"%d %d", row, col);
	return MultiTableValue[row][col];
}

- (NSString *)getActionByValue:(int)val {
	switch (val) {
		case 0:
			return @"You should stand";
			break;
		case 1:
			return @"You should hit";
			break;
		case 2:
			//return @"You should split";
			return @"You should hit";
			break;
		case 3:
			//return @"You should double";
			return @"You should hit";
			break;
		default:
			break;
	}
	return @"";
}

#pragma mark ACTIONS
- (void)viewResult:(NSTimer *)t {
	tick_++; 
	if(tick_ == 1) {
		[matchResult_ setHidden:NO];
	} 
	else {
		[matchResult_ setHidden:YES];
		[self endOneGame];
		[t invalidate];
	}
}
- (void)showActionAdviceStatement {
	int val = [self getValueOfActionByDealerCard:dealerCards_[1] PlayerCardsArr:playerCards_ number:playerCardCount_];
	NSString * str = [self getActionByValue:val];
//	[actionAdviceStat_ setText:str];
	[tooltip.view setHidden:NO];
	[tooltip setDealerCard:dealerCards_[1]];
	[tooltip setPlayerCardValue:[self countPlayerHand]];
	[tooltip setAction:str];
}
- (void)showBettingAdviceStatement {
	if(trueCountValue_ < 1.0) {
		[stateLb_ setText:@"True count is smaller than 1"];
		[betAdviceStat_ setText:@"Bet your base amount"];
	}
	else if(trueCountValue_ < 3.0) {
		[stateLb_ setText:@"True count is smaller than 3"];
		[betAdviceStat_ setText:@"Bet 2 times your base unit"];
	}
	else if(trueCountValue_ < 5.0) {
		[stateLb_ setText:@"True count is smaller than 5"];
		[betAdviceStat_ setText:@"Bet 3 times your base unit"];
	}
	else if(trueCountValue_ < 7.0) {
		[stateLb_ setText:@"True count is smaller than 7"];
		[betAdviceStat_ setText:@"Bet 4 times your base unit"];
	}
	else {
		[stateLb_ setText:@"True count is greater than 7"];
		[betAdviceStat_ setText:@"Bet 5 times your base unit"];
	}
}
- (void)disableAll {
	[hitBtn_ setEnabled:NO];
	[dealBtn_ setEnabled:NO];
	[splitBtn_ setEnabled:NO];
	[standBtn_ setEnabled:NO];
	[doubleBtn_ setEnabled:NO];
}

- (void)enabledAll {
	[hitBtn_ setEnabled:YES];
	[dealBtn_ setEnabled:YES];
	[splitBtn_ setEnabled:YES];
	[standBtn_ setEnabled:YES];
	[doubleBtn_ setEnabled:YES];
}

#pragma mark CALLBACK_FUNC
- (void)viewDidAppear {
	
}

- (void)viewDidLoad {
    [super viewDidLoad];	
	[MusicManager setEnabled:YES];
	[MusicManager playMusicTrack:@"CasinoNoise" withRepeat:YES];
	tooltip = [[TooltipController alloc] init];
	[self.view addSubview:tooltip.view];
	
	[tooltip.view setHidden:YES];
	
	[self setLandscapeToView:self.view];
	[hitBtn_ setHidden:YES];
	[doubleBtn_ setHidden:YES];
	[splitBtn_ setHidden:YES];
	[standBtn_ setHidden:YES];
	
	[stateLb_ setText:@""];
	[betAdviceStat_ setText:@""];
	[actionAdviceStat_ setText:@""];
	[curCardCount_ setText:@"KO system"];
	[remainDeck_ setText:@"remaining deck: 6"];
		
	currentCardCounting = KOCounting;
	currentDeckMode = DECK_MODE_SINGLE;
	
	popup_ = [[PopupView alloc] initWithFrame:CGRectMake(300, 60, 150, 200)];
	[popup_ setDelegate:self];
	[self.view addSubview:popup_];
	[popup_ setHidden:YES];
	
	for(int i = 0; i < 5; i++) {
		playerCardsView_[i] = [[UIImageView alloc] initWithFrame:animator_.frame];
		dealerCardsView_[i] = [[UIImageView alloc] initWithFrame:animator_.frame];
		
		[self.view addSubview:playerCardsView_[i]];
		[self.view addSubview:dealerCardsView_[i]];
		
		[playerCardsView_[i] setHidden:YES];
		[dealerCardsView_[i] setHidden:YES];
	}
	
	[dealerCardsView_[0] setFrame:CGRectMake(DEALER_CARD_POS_X, DEALER_CARD_POS_Y, animator_.frame.size.width, animator_.frame.size.height)];
	//faceupCardView = [[UIImageView alloc] initWithFrame:animator_.frame];
//	[faceupCardView setHidden:YES];
//	[self.view addSubview:faceupCardView];
	//[faceupCardView setImage:[UIImage imageNamed:@"PlayCard1AL.png"]];
	[self initAll];
	
}

- (void)viewDidUnload {
	[MusicManager stopCurrentTrack];
}

- (void)setLandscapeToView:(UIView *)view
{
	//CGRect v = view.frame;
	[[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeRight animated:NO];
	CGAffineTransform landscapeTransform = CGAffineTransformMakeRotation(M_PI_2);
	landscapeTransform = CGAffineTransformTranslate (landscapeTransform, -50.0, +100.0);
	[view setTransform:landscapeTransform];
	//CGRect t = view.frame;
	
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
	//return (toInterfaceOrientation == UIInterfaceOrientationLandscapeRight);
	return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];	
}

- (void)dealloc {
	for(int i = 0; i < 5; i++) {
		[playerCardsView_[i] release];
		//[tmpPlayerCardsView_[i] release];
		[dealerCardsView_[i]  release];
	}
	//[musicPlayer release];
	[popup_ release];
    [super dealloc];
	[[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationPortrait animated:NO];
}

@end
